from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponseForbidden, JsonResponse
from django.utils import timezone
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .forms import AdminLoginForm, ArticleForm, CategoryForm, DepartmentForm, UserGroupForm, PermissionGroupForm, PermissionForm, ArticleReviewForm, CategoryReviewProcessForm
from content.models import Article, Category, Department, UserGroup, PermissionGroup, Permission, ArticleReview, CategoryReviewProcess

from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import os
import json
import random
import string
from datetime import datetime

@csrf_exempt
@login_required
def ueditor_handler(request):
    """
    UEditor后端处理函数
    """
    action = request.GET.get('action')
    
    # 获取UEditor配置
    ueditor_settings = getattr(settings, 'UEDITOR_SETTINGS', {})
    image_max_size = ueditor_settings.get('image_max_size', 2 * 1024 * 1024)  # 默认2MB
    file_max_size = ueditor_settings.get('file_max_size', 50 * 1024 * 1024)    # 默认50MB
    
    if action == 'config':
        # 返回配置信息
        config = {
            "imageActionName": "uploadimage",
            "imageFieldName": "upfile",
            "imageMaxSize": image_max_size,
            "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
            "imageCompressEnable": True,
            "imageCompressBorder": 1600,
            "imageInsertAlign": "none",
            "imageUrlPrefix": "",
            "imagePathFormat": "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
            
            "fileActionName": "uploadfile",
            "fileFieldName": "upfile",
            "fileMaxSize": file_max_size,
            "fileAllowFiles": [
                ".png", ".jpg", ".jpeg", ".gif", ".bmp",
                ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
                ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
                ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
            ],
            "filePathFormat": "upload/file/{yyyy}{mm}{dd}/{time}{rand:6}",
            "fileUrlPrefix": "",
            "fileManagerListPath": "upload/file/",
            "fileManagerListSize": 20,
            "fileManagerAllowFiles": [
                ".png", ".jpg", ".jpeg", ".gif", ".bmp",
                ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
                ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
                ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
            ]
        }
        return JsonResponse(config)
    
    elif action == 'uploadimage':
        return handle_upload_file(request, 'image')
    
    elif action == 'uploadfile':
        return handle_upload_file(request, 'file')
    
    return JsonResponse({'state': 'error'})

def handle_upload_file(request, file_type):
    """
    处理文件上传
    """
    # 获取UEditor配置
    ueditor_settings = getattr(settings, 'UEDITOR_SETTINGS', {})
    image_max_size = ueditor_settings.get('image_max_size', 2 * 1024 * 1024)  # 默认2MB
    file_max_size = ueditor_settings.get('file_max_size', 50 * 1024 * 1024)    # 默认50MB
    
    if request.method == 'POST':
        try:
            # 获取上传的文件
            upfile = request.FILES.get('upfile')
            if not upfile:
                return JsonResponse({'state': '文件为空'})
            
            # 检查文件大小
            if file_type == 'image' and upfile.size > image_max_size:
                return JsonResponse({'state': f'图片大小不能超过{image_max_size // (1024 * 1024)}MB'})
            elif file_type == 'file' and upfile.size > file_max_size:
                return JsonResponse({'state': f'文件大小不能超过{file_max_size // (1024 * 1024)}MB'})
            
            # 检查文件扩展名
            ext = os.path.splitext(upfile.name)[1].lower()
            if file_type == 'image':
                allowed_exts = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]
            else:
                allowed_exts = [
                    ".png", ".jpg", ".jpeg", ".gif", ".bmp",
                    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
                    ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
                    ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
                ]
            
            if ext not in allowed_exts:
                return JsonResponse({'state': '不支持的文件类型'})
            
            # 生成文件名
            filename = generate_filename(upfile.name)
            
            # 确定保存路径
            if file_type == 'image':
                upload_path = os.path.join('upload', 'image', datetime.now().strftime('%Y%m%d'))
            else:
                upload_path = os.path.join('upload', 'file', datetime.now().strftime('%Y%m%d'))
            
            # 确保目录存在
            full_upload_path = os.path.join(settings.MEDIA_ROOT, upload_path)
            os.makedirs(full_upload_path, exist_ok=True)
            
            # 保存文件
            file_path = os.path.join(full_upload_path, filename)
            relative_path = os.path.join(upload_path, filename).replace('\\', '/')
            
            with open(file_path, 'wb+') as destination:
                for chunk in upfile.chunks():
                    destination.write(chunk)
            
            # 返回成功响应
            return JsonResponse({
                'state': 'SUCCESS',
                'url': os.path.join(settings.MEDIA_URL, relative_path).replace('\\', '/'),
                'title': filename,
                'original': upfile.name,
                'type': ext,
                'size': upfile.size
            })
        except Exception as e:
            return JsonResponse({'state': f'上传失败: {str(e)}'})
    
    return JsonResponse({'state': 'error'})

def generate_filename(original_name):
    """
    生成唯一文件名
    """
    ext = os.path.splitext(original_name)[1]
    timestamp = str(int(datetime.now().timestamp() * 1000))
    random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=6))
    return f"{timestamp}{random_str}{ext}"

def admin_login(request):
    """管理员登录视图"""
    if request.method == 'POST':
        form = AdminLoginForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('custom_admin:dashboard')
            else:
                messages.error(request, '用户名或密码错误')
    else:
        form = AdminLoginForm()
    return render(request, 'custom_admin/login.html', {'form': form})

@login_required
def admin_logout(request):
    """管理员登出视图"""
    logout(request)
    return redirect('custom_admin:login')

@login_required
def dashboard(request):
    """管理后台首页"""
    # 统计数据
    article_count = Article.objects.count()
    category_count = Category.objects.count()
    published_count = Article.objects.filter(published=True).count()
    department_count = Department.objects.count()
    user_group_count = UserGroup.objects.count()
    permission_group_count = PermissionGroup.objects.count()
    
    # 待审核文章统计
    pending_count = Article.objects.filter(status=Article.PENDING).count()
    first_approved_count = Article.objects.filter(status=Article.FIRST_APPROVED).count()
    
    context = {
        'article_count': article_count,
        'category_count': category_count,
        'published_count': published_count,
        'department_count': department_count,
        'user_group_count': user_group_count,
        'permission_group_count': permission_group_count,
        'pending_count': pending_count,
        'first_approved_count': first_approved_count,
    }
    return render(request, 'custom_admin/dashboard.html', context)

@login_required
def article_list(request):
    """文章列表"""
    status = request.GET.get('status', '')
    title = request.GET.get('title', '')
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    
    # 确保page_size是有效值
    try:
        page_size = int(page_size)
        if page_size not in [10, 20, 50]:
            page_size = 10
    except (ValueError, TypeError):
        page_size = 10
    
    articles = Article.objects.all().order_by('-created_at')
    
    if status:
        articles = articles.filter(status=status)
    
    if title:
        articles = articles.filter(title__icontains=title)
    
    # 创建分页器
    paginator = Paginator(articles, page_size)
    
    try:
        articles_page = paginator.page(page)
    except PageNotAnInteger:
        articles_page = paginator.page(1)
    except EmptyPage:
        articles_page = paginator.page(paginator.num_pages)
    
    return render(request, 'custom_admin/article_list.html', {
        'articles': articles_page,
        'status': status,
        'title': title,
        'page_size': page_size,
        'paginator': paginator
    })

@login_required
def article_create(request):
    """创建文章"""
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.author = request.user
            article.save()
            # 检查表单是否有save_m2m方法
            if hasattr(form, 'save_m2m'):
                # 保存文章分类关联
                form.save_m2m()
            messages.success(request, '文章创建成功！')
            return redirect('custom_admin:article_list')
    else:
        form = ArticleForm()
    return render(request, 'custom_admin/article_form.html', {'form': form})

@login_required
def article_edit(request, pk):
    """编辑文章"""
    article = get_object_or_404(Article, pk=pk)
    if request.method == 'POST':
        form = ArticleForm(request.POST, instance=article)
        if form.is_valid():
            # 检查表单是否有save_m2m方法
            if hasattr(form, 'save_m2m'):
                form.save()
                # 保存文章分类关联
                form.save_m2m()
            else:
                # 如果没有save_m2m方法，直接保存
                form.save()
            messages.success(request, '文章更新成功！')
            return redirect('custom_admin:article_list')
    else:
        form = ArticleForm(instance=article)
    return render(request, 'custom_admin/article_form.html', {
        'form': form, 
        'article': article
    })

@login_required
def article_delete(request, pk):
    """删除文章"""
    article = get_object_or_404(Article, pk=pk)
    if request.method == 'POST':
        article.delete()
        messages.success(request, '文章删除成功！')
        return redirect('custom_admin:article_list')
    return render(request, 'custom_admin/article_confirm_delete.html', {'article': article})

@login_required
def article_submit_for_review(request, pk):
    """提交文章审核"""
    article = get_object_or_404(Article, pk=pk)
    if article.author != request.user and not request.user.is_superuser:
        return HttpResponseForbidden("您没有权限执行此操作")
    
    if request.method == 'POST':
        article.status = Article.PENDING
        article.submitted_at = timezone.now()
        article.save()
        messages.success(request, '文章已提交审核！')
        return redirect('custom_admin:article_list')
    
    return render(request, 'custom_admin/article_submit_confirm.html', {'article': article})

@login_required
def article_review_list(request):
    """审核文章列表"""
    # 根据用户角色筛选需要审核的文章
    user_groups = request.user.usergroup_set.all()
    
    # 获取需要初审的文章
    if request.user.is_superuser:
        pending_articles = Article.objects.filter(status=Article.PENDING)
    else:
        # 检查用户是否属于任何初审员组
        first_reviewer_groups = CategoryReviewProcess.objects.filter(
            first_reviewer_group__in=user_groups
        ).values_list('category', flat=True)
        
        pending_articles = Article.objects.filter(
            status=Article.PENDING,
            articlecategory__category__categoryreviewprocess__in=first_reviewer_groups
        ).distinct()
    
    # 获取需要终审的文章
    if request.user.is_superuser:
        first_approved_articles = Article.objects.filter(status=Article.FIRST_APPROVED)
    else:
        # 检查用户是否属于任何终审员组
        final_reviewer_groups = CategoryReviewProcess.objects.filter(
            final_reviewer_group__in=user_groups
        ).values_list('category', flat=True)
        
        first_approved_articles = Article.objects.filter(
            status=Article.FIRST_APPROVED,
            articlecategory__category__categoryreviewprocess__in=final_reviewer_groups
        ).distinct()
    
    context = {
        'pending_articles': pending_articles,
        'first_approved_articles': first_approved_articles,
    }
    return render(request, 'custom_admin/article_review_list.html', context)

@login_required
def article_first_review(request, pk):
    """初审文章"""
    article = get_object_or_404(Article, pk=pk)
    
    # 检查用户是否有初审权限
    user_groups = request.user.usergroup_set.all()
    if not request.user.is_superuser:
        first_reviewer_groups = CategoryReviewProcess.objects.filter(
            first_reviewer_group__in=user_groups
        ).exists()
        
        if not first_reviewer_groups:
            return HttpResponseForbidden("您没有初审权限")
    
    if request.method == 'POST':
        form = ArticleReviewForm(request.POST)
        if form.is_valid():
            action = form.cleaned_data['action']
            comment = form.cleaned_data['comment']
            
            # 创建审核记录
            review = ArticleReview(
                article=article,
                reviewer=request.user,
                status_before=article.status,
                comment=comment
            )
            
            if action == 'approve':
                article.status = Article.FIRST_APPROVED
                article.first_reviewed_at = timezone.now()
                review.action = '通过'
                review.status_after = Article.FIRST_APPROVED
                messages.success(request, '初审通过！')
            else:
                article.status = Article.REJECTED
                article.first_reviewed_at = timezone.now()
                review.action = '拒绝'
                review.status_after = Article.REJECTED
                messages.success(request, '初审拒绝！')
            
            article.save()
            review.save()
            
            return redirect('custom_admin:article_review_list')
    else:
        form = ArticleReviewForm()
    
    # 获取审核历史
    review_history = ArticleReview.objects.filter(article=article)
    
    context = {
        'article': article,
        'form': form,
        'review_history': review_history,
    }
    return render(request, 'custom_admin/article_first_review.html', context)

@login_required
def article_final_review(request, pk):
    """终审文章"""
    article = get_object_or_404(Article, pk=pk)
    
    # 检查用户是否有终审权限
    user_groups = request.user.usergroup_set.all()
    if not request.user.is_superuser:
        final_reviewer_groups = CategoryReviewProcess.objects.filter(
            final_reviewer_group__in=user_groups
        ).exists()
        
        if not final_reviewer_groups:
            return HttpResponseForbidden("您没有终审权限")
    
    if request.method == 'POST':
        form = ArticleReviewForm(request.POST)
        if form.is_valid():
            action = form.cleaned_data['action']
            comment = form.cleaned_data['comment']
            
            # 创建审核记录
            review = ArticleReview(
                article=article,
                reviewer=request.user,
                status_before=article.status,
                comment=comment
            )
            
            if action == 'approve':
                article.status = Article.APPROVED
                article.final_reviewed_at = timezone.now()
                review.action = '通过'
                review.status_after = Article.APPROVED
                
                # 检查是否自动发布
                categories = article.articlecategory_set.values_list('category', flat=True)
                auto_publish = CategoryReviewProcess.objects.filter(
                    category__in=categories,
                    is_active=True,
                    auto_publish=True
                ).exists()
                
                if auto_publish:
                    article.status = Article.PUBLISHED
                    article.published = True
                    article.published_at = timezone.now()
                    review.status_after = Article.PUBLISHED
                    messages.success(request, '终审通过并已发布！')
                else:
                    messages.success(request, '终审通过！')
            else:
                article.status = Article.REJECTED
                article.final_reviewed_at = timezone.now()
                review.action = '拒绝'
                review.status_after = Article.REJECTED
                messages.success(request, '终审拒绝！')
            
            article.save()
            review.save()
            
            return redirect('custom_admin:article_review_list')
    else:
        form = ArticleReviewForm()
    
    # 获取审核历史
    review_history = ArticleReview.objects.filter(article=article)
    
    context = {
        'article': article,
        'form': form,
        'review_history': review_history,
    }
    return render(request, 'custom_admin/article_final_review.html', context)

@login_required
def article_publish(request, pk):
    """发布文章"""
    article = get_object_or_404(Article, pk=pk)
    
    # 只有超级用户或审核通过的文章才能发布
    if not request.user.is_superuser and article.status != Article.APPROVED:
        return HttpResponseForbidden("您没有权限执行此操作")
    
    if request.method == 'POST':
        article.status = Article.PUBLISHED
        article.published = True
        article.published_at = timezone.now()
        article.save()
        messages.success(request, '文章已发布！')
        return redirect('custom_admin:article_list')
    
    return render(request, 'custom_admin/article_publish_confirm.html', {'article': article})

@login_required
def article_withdraw(request, pk):
    """撤回文章"""
    article = get_object_or_404(Article, pk=pk)
    
    # 只有超级用户才能撤回已发布的文章
    if not request.user.is_superuser:
        return HttpResponseForbidden("您没有权限执行此操作")
    
    if request.method == 'POST':
        article.status = Article.WITHDRAWN
        article.published = False
        article.withdrawn_at = timezone.now()
        article.save()
        messages.success(request, '文章已撤回！')
        return redirect('custom_admin:article_list')
    
    return render(request, 'custom_admin/article_withdraw_confirm.html', {'article': article})

@login_required
def category_list(request):
    """分类列表"""
    # 获取顶级分类（没有父分类的分类）
    root_categories = Category.objects.filter(parent=None)
    all_categories = Category.objects.all()
    return render(request, 'custom_admin/category_list.html', {
        'categories': root_categories,
        'all_categories': all_categories
    })

@login_required
def category_create(request):
    """创建分类"""
    parent_id = request.GET.get('parent')
    initial = {}
    if parent_id:
        try:
            parent = Category.objects.get(pk=parent_id)
            initial['parent'] = parent
        except Category.DoesNotExist:
            pass
    
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '分类创建成功！')
            return redirect('custom_admin:category_list')
    else:
        form = CategoryForm(initial=initial)
    return render(request, 'custom_admin/category_form.html', {'form': form, 'parent': initial.get('parent')})

@login_required
def category_edit(request, pk):
    """编辑分类"""
    category = get_object_or_404(Category, pk=pk)
    if request.method == 'POST':
        form = CategoryForm(request.POST, instance=category)
        if form.is_valid():
            form.save()
            messages.success(request, '分类更新成功！')
            return redirect('custom_admin:category_list')
    else:
        form = CategoryForm(instance=category)
    return render(request, 'custom_admin/category_form.html', {
        'form': form, 
        'category': category
    })

@login_required
def category_delete(request, pk):
    """删除分类"""
    category = get_object_or_404(Category, pk=pk)
    if request.method == 'POST':
        category.delete()
        messages.success(request, '分类删除成功！')
        return redirect('custom_admin:category_list')
    return render(request, 'custom_admin/category_confirm_delete.html', {'category': category})

@login_required
def category_review_process(request, pk):
    """栏目审核流程配置"""
    category = get_object_or_404(Category, pk=pk)
    
    # 获取或创建审核流程配置
    review_process, created = CategoryReviewProcess.objects.get_or_create(
        category=category,
        defaults={
            'review_level': 2,
            'auto_publish': False,
            'notify_author': True,
            'notify_reviewer': True,
            'is_active': True
        }
    )
    
    if request.method == 'POST':
        form = CategoryReviewProcessForm(request.POST, instance=review_process)
        if form.is_valid():
            form.save()
            messages.success(request, '审核流程配置已更新！')
            return redirect('custom_admin:category_list')
    else:
        form = CategoryReviewProcessForm(instance=review_process)
    
    context = {
        'category': category,
        'form': form,
    }
    return render(request, 'custom_admin/category_review_process.html', context)

# 部门管理视图
@login_required
def department_list(request):
    """部门列表"""
    departments = Department.objects.filter(parent=None)  # 获取顶级部门
    all_departments = Department.objects.all()
    return render(request, 'custom_admin/department_list.html', {
        'departments': departments,
        'all_departments': all_departments
    })

@login_required
def department_create(request):
    """创建部门"""
    if request.method == 'POST':
        form = DepartmentForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '部门创建成功！')
            return redirect('custom_admin:department_list')
    else:
        form = DepartmentForm()
    return render(request, 'custom_admin/department_form.html', {'form': form})

@login_required
def department_create_sub(request, pk):
    """创建子部门"""
    parent = get_object_or_404(Department, pk=pk)
    if request.method == 'POST':
        form = DepartmentForm(request.POST)
        if form.is_valid():
            department = form.save(commit=False)
            department.parent = parent
            department.save()
            messages.success(request, '子部门创建成功！')
            return redirect('custom_admin:department_list')
    else:
        form = DepartmentForm(initial={'parent': parent})
    return render(request, 'custom_admin/department_form.html', {
        'form': form,
        'parent': parent
    })

@login_required
def department_edit(request, pk):
    """编辑部门"""
    department = get_object_or_404(Department, pk=pk)
    if request.method == 'POST':
        form = DepartmentForm(request.POST, instance=department)
        if form.is_valid():
            form.save()
            messages.success(request, '部门更新成功！')
            return redirect('custom_admin:department_list')
    else:
        form = DepartmentForm(instance=department)
    return render(request, 'custom_admin/department_form.html', {
        'form': form,
        'department': department
    })

@login_required
def department_delete(request, pk):
    """删除部门"""
    department = get_object_or_404(Department, pk=pk)
    if department.get_children().exists():
        messages.error(request, '该部门下存在子部门，无法删除！')
        return redirect('custom_admin:department_list')
    
    if request.method == 'POST':
        department.is_active = False  # 软删除
        department.save()
        messages.success(request, '部门删除成功！')
        return redirect('custom_admin:department_list')
    return render(request, 'custom_admin/department_confirm_delete.html', {'department': department})

# 用户组管理视图
@login_required
def user_group_list(request):
    """用户组列表"""
    user_groups = UserGroup.objects.all()
    return render(request, 'custom_admin/user_group_list.html', {'user_groups': user_groups})

@login_required
def user_group_create(request):
    """创建用户组"""
    if request.method == 'POST':
        form = UserGroupForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '用户组创建成功！')
            return redirect('custom_admin:user_group_list')
    else:
        form = UserGroupForm()
    return render(request, 'custom_admin/user_group_form.html', {'form': form})

@login_required
def user_group_edit(request, pk):
    """编辑用户组"""
    user_group = get_object_or_404(UserGroup, pk=pk)
    if request.method == 'POST':
        form = UserGroupForm(request.POST, instance=user_group)
        if form.is_valid():
            form.save()
            messages.success(request, '用户组更新成功！')
            return redirect('custom_admin:user_group_list')
    else:
        form = UserGroupForm(instance=user_group)
    return render(request, 'custom_admin/user_group_form.html', {
        'form': form,
        'user_group': user_group
    })

@login_required
def user_group_delete(request, pk):
    """删除用户组"""
    user_group = get_object_or_404(UserGroup, pk=pk)
    if request.method == 'POST':
        user_group.is_active = False  # 软删除
        user_group.save()
        messages.success(request, '用户组删除成功！')
        return redirect('custom_admin:user_group_list')
    return render(request, 'custom_admin/user_group_confirm_delete.html', {'user_group': user_group})

# 权限组管理视图
@login_required
def permission_group_list(request):
    """权限组列表"""
    permission_groups = PermissionGroup.objects.all()
    return render(request, 'custom_admin/permission_group_list.html', {'permission_groups': permission_groups})

@login_required
def permission_group_create(request):
    """创建权限组"""
    if request.method == 'POST':
        form = PermissionGroupForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '权限组创建成功！')
            return redirect('custom_admin:permission_group_list')
    else:
        form = PermissionGroupForm()
    return render(request, 'custom_admin/permission_group_form.html', {'form': form})

@login_required
def permission_group_edit(request, pk):
    """编辑权限组"""
    permission_group = get_object_or_404(PermissionGroup, pk=pk)
    if request.method == 'POST':
        form = PermissionGroupForm(request.POST, instance=permission_group)
        if form.is_valid():
            form.save()
            messages.success(request, '权限组更新成功！')
            return redirect('custom_admin:permission_group_list')
    else:
        form = PermissionGroupForm(instance=permission_group)
    return render(request, 'custom_admin/permission_group_form.html', {
        'form': form,
        'permission_group': permission_group
    })

@login_required
def permission_group_delete(request, pk):
    """删除权限组"""
    permission_group = get_object_or_404(PermissionGroup, pk=pk)
    if request.method == 'POST':
        permission_group.is_active = False  # 软删除
        permission_group.save()
        messages.success(request, '权限组删除成功！')
        return redirect('custom_admin:permission_group_list')
    return render(request, 'custom_admin/permission_group_confirm_delete.html', {'permission_group': permission_group})

# 权限管理视图
@login_required
def permission_list(request):
    """权限列表"""
    permissions = Permission.objects.all()
    return render(request, 'custom_admin/permission_list.html', {'permissions': permissions})

@login_required
def permission_create(request):
    """创建权限"""
    if request.method == 'POST':
        form = PermissionForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '权限创建成功！')
            return redirect('custom_admin:permission_list')
    else:
        form = PermissionForm()
    return render(request, 'custom_admin/permission_form.html', {'form': form})

@login_required
def permission_edit(request, pk):
    """编辑权限"""
    permission = get_object_or_404(Permission, pk=pk)
    if request.method == 'POST':
        form = PermissionForm(request.POST, instance=permission)
        if form.is_valid():
            form.save()
            messages.success(request, '权限更新成功！')
            return redirect('custom_admin:permission_list')
    else:
        form = PermissionForm(instance=permission)
    return render(request, 'custom_admin/permission_form.html', {
        'form': form,
        'permission': permission
    })

@login_required
def permission_delete(request, pk):
    """删除权限"""
    permission = get_object_or_404(Permission, pk=pk)
    if request.method == 'POST':
        permission.delete()
        messages.success(request, '权限删除成功！')
        return redirect('custom_admin:permission_list')
    return render(request, 'custom_admin/permission_confirm_delete.html', {'permission': permission})